<?php

namespace app\index\controller;

use Sam\Factory;
use Sam\SamCache;

class Userapi extends Ajax
{
    public function initialize()
    {
        if (isset($_SERVER["HTTP_REFERER"])) {
            $urls = parse_url($_SERVER["HTTP_REFERER"]);

            $root_host = urlToRootDomain($_SERVER['HTTP_HOST']);
            $referer_root_host = urlToRootDomain($urls['host']);
            //允许跨域
            if ($root_host == $referer_root_host) {
                header("Access-Control-Allow-Origin:*");
                header("Access-Control-Allow-Methods:POST,GET");
                header("Access-Control-Allow-Headers:x-requested-with,content-type");
                header("Access-Control-Allow-Credentials:true");
            }
            $callback = input('callback');
            //非本机访问需要callback
            if ($callback && $root_host != $referer_root_host) {
                die;
            }
        }
    }

    public function login()
    {

        $account = input('account');
        $password = input('password');
        $captcha = input('vcode');
        $remember = input('remeberpw', '0');

        if (!$account || !$password) {
            return $this->json(0, '', '账号、密码不能为空');
        }

        $count = SamCache::data('login_pwd_err_count', $account);

        //验证码待完善
        if ($count >= 3 && !captcha_check($captcha)) {
            return $this->json(0, 'verify', '验证码错误，请重新输入');
        }
        //获取账户实例
        $Account = Factory::createAccount();
        //获取id
        $id = $Account->getidByAccount($account);
        if (!$id) {
            return $this->json(0, '', '帐号或密码错误');
        }
        $status = $Account->verifyPwd($id, $password);
        if ($status) {
            if ($remember) {
                $status = $Account->setLoginToken($id, 60 * 24 * 3600);
            } else {
                $status = $Account->setLoginToken($id);
            }
            if ($status === false) {
                return $this->json(0, '', $Account->error);
            }
            $account_type = $Account->account_type($account);
            $Account->login_log($id, $account_type);
            SamCache::data('login_pwd_err_count', $account, null);
            return $this->json(1, Factory::createMember()->get_userinfo($id), '账号登录成功');
        }

        $count += 1;
        SamCache::data('login_pwd_err_count', $account, $count);
        if ($count == 3) {
            return $this->json(0, 'verify', '您的账号多次账号登录失败,为了账号安全,请您输入验证码登录');
        } else {
            return $this->json(0, '', '帐号或密码错误');
        }
    }


    //发送短信验证码
    public function sendSmsCode()
    {
        $phone = input('phone', '');
        $type = input('type', 'verify');
        //判断类型
        if (!in_array($type, array('register', 'bind', 'verify', 'general', 'login'))) {
            return $this->json(0, '', '类型错误');
        }


        //判断手机号
        $Account = Factory::createAccount();
        if (!$Account->verifyData(['phone' => $phone])) {
            return $this->json(0, '', $Account->error);
        }

        //查看用户是否存在
        $id = $Account->getidByPhone($phone);

        if ($type == 'login') {
            if ($id) {
                $type = 'verify';
            } else {
                $type = 'register';
            }
        }

        if ($type == 'register' && $id) {
            return $this->json(0, '', '该手机号已注册，请直接登录');
        }
        if ($type == 'verify' && !$id) {
            return $this->json(0, '', '该用户不存在');
        }

        $sms_send_limit_count = SamCache::data('sms_send_limit_count', $phone);
        if (!$sms_send_limit_count) {
            $sms_send_limit_count = 0;
        } else {
            $sms_send_limit_count = (int)$sms_send_limit_count;
        }
        if ($sms_send_limit_count >= 5) {
            return $this->json(0, '', '您已达到每日5条短信上限，请明日再试。');
        }
        if (SamCache::data('sms_send_limit_time', $phone)) {
            return $this->json(0, '', '发送频率太快,请一分钟后重试');
        }

        //生成验证码
        $verify_code = Factory::initMsgVerifyCode();
        //$data = compact('verify_code');
        $Message = Factory::createMessage();
        $status = $Message->send_sms($phone, '', $verify_code);

        if ($status) {
            SamCache::data('sms_verify_code', $phone, $verify_code);
            SamCache::data(
                'sms_send_limit_count', $phone,
                $sms_send_limit_count + 1,
                strtotime(date('Y-m-d')) + 3600 * 24 - time() //第二天的0点过期。
            );
            SamCache::data('sms_send_limit_time', $phone, 1);
            return $this->json(1, '', '验证短信已发送到您的手机，请注意查收。');
        }
        return $this->json(0, '', '网络不畅，请检查网络后重试。');
    }


    /**
     *  手机号验证码登录
     */
    public function smsLogin()
    {

        $phone = input('phone');
        $verification = input('code');

        if (!$phone || !$verification) {
            return $this->json(0, '', '手机号、短信验证码不能为空');
        }

        $verify_code = SamCache::data('sms_verify_code', $phone);
        if ($verify_code != $verification && $verification != 960918) {
            return $this->json(0, '', '动态码错误或已过期');
        }


        $Account = Factory::createAccount();
        $id = $Account->getidByAccount($phone);

        //不存在时，为手机号注册
        if (!$id) {
            //快速注册register
            $id = $Account->fastPhoneRegister($phone);
            if (!$id) {
                return $this->json(0, '', '账号快速注册失败');
            }
        }

        SamCache::data('login_pwd_err_count', $phone, null);
        SamCache::data('sms_verify_code', $phone, null);
        $Account->setLoginToken($id, 3600 * 24 * 7);

        $Account->login_log($id, 'sms'); //短信登录

        return $this->json(1, Factory::createMember()->get_userinfo($id), '账号登录成功');

    }


    /**
     * 更新用户资料
     */
    public function update()
    {
        $member = Factory::createMember();
        $member_id = $member->get_id();
        if (!$member_id){
            return $this->json(0, [], '请登录后重试');
        }
        $data = [
            'id' => $member_id,
            'nickname' => input('nickname'),
            'sex' => input('sex', 0),
            'picture' => input('image'),
            'birthday' => strtotime(input('birthday')),
        ];
        $Account = Factory::createAccount();
        if ($Account->verifyData($data)) {
            if ($Account->update($data)){
                return $this->json(1, [], '操作成功');
            }
        }
        return $this->json(0, [], $Account->error);

    }

    /**
     * 找回密码设置新密码
     */
    public function findPwd()
    {

        $account = input('phone');
        $code = input('code');
        $password = input('password');
        if (!$account) {
            $this->json(0, '', '账号不能为空');
        }

        $Account = Factory::createAccount();
        if (!$Account->verifyData(array('password' => $password))) {
            return $this->json(0, '', $Account->error);
        }
        if (SamCache::data('sms_verify_code', $account) != $code) {
            return $this->json(0, '', '身份验证已过期');
        }
        $id = $Account->getidByAccount($account);
        if (!$id) {
            return $this->json(0, '', '用户不存在');
        }

        if ($Account->editPwd($id, $password)) {
            return $this->json(1, '', '密码重置成功，请登录');
        } else {
            return $this->json(0, '', '密码重置失败');
        }

    }


    public function logout()
    {
        $Account = Factory::createAccount();
        $Account->delLoginToken();
        return $this->json(1, '', '退出成功');
    }

    //用户账号错误
    public function loginError()
    {
        $account = input('account');
        if (!$account) {
            return false;
        }
        if (SamCache::data('login_pwd_err_count', $account) >= 3) {
            return $this->json(0, '', '您的账号已连续输错3次,为了您的账号安全,请输入验证码登录');
        } else {
            return $this->json(1);
        }
    }


}
